package com.aube.interact.fighter.card;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;

import java.lang.ref.WeakReference;

/**
 * Created by huyaonan on 16/4/5.
 */
public class ExtendImageSpan extends DynamicDrawableSpan {

    private Bitmap mBitmap;
    private Context mContext;
    private float targetHeight=0;

    public ExtendImageSpan(Context context, Bitmap b, float targetHeight) {
        super(DynamicDrawableSpan.ALIGN_BASELINE);
        this.mBitmap = b;
        this.mContext = context;
        this.targetHeight = targetHeight;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {

        Drawable b = getCachedDrawable();
        canvas.save();
//        int transY = top;//解决和文字无法对齐的bug

//        int transY = bottom - b.getBounds().bottom;
//        if (mVerticalAlignment == ALIGN_BASELINE) {
//            transY -= paint.getFontMetricsInt().descent -2;
//        }

        int transY = ((bottom - top) - b.getBounds().bottom) / 2 + top + 2;

        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }

    private Drawable getCachedDrawable() {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;

        if (wr != null)
            d = wr.get();

        if (d == null) {
            d = getDrawable();
            mDrawableRef = new WeakReference<Drawable>(d);
        }

        return d;
    }

    private WeakReference<Drawable> mDrawableRef;

    @Override
    public Drawable getDrawable() {
        Drawable drawable = null;
        try {
            int width = mBitmap.getWidth();
            int height = mBitmap.getHeight();
            float targetWidth = targetHeight*width/height;
            drawable = new BitmapDrawable(mContext.getResources(), mBitmap);
            drawable.setBounds(0, 0, (int)targetWidth, (int)targetHeight);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return drawable;
    }
}
